package com.xiaotu.util;

import com.xiaotu.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * @author 小土
 */
public class CrowdUtil {
    /**
     * 判断当前请求是否为Ajax请求
     * @param httpServletRequest
     * @return
     * true 是Ajax请求
     * false 不是Ajax请求
     */
    public static boolean judgeRequestType(HttpServletRequest httpServletRequest){
        //获取请求消息头
        String accept = httpServletRequest.getHeader("Accept");
        String header = httpServletRequest.getHeader("X-Requested-With");
        //判断
          return (accept != null && accept.contains("application/json"))
                ||
                (header != null && header.contains("XMLHttpRequest"));
    }

    /**
     * 对明文字符串进行md5加密
     * @param source 传入加密的字符串
     * @return 加密后的结果
     */
    public static String md5(String source){
        //1.判断source是否有效
        if(source == null || source.length() ==0){
            //2.如果不是有效的字符串抛出异常
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }
        //3.获取MessageDigest对象
        try {
            String algorithm = "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            //获取明文字符串对应的字节数组
            byte[] bytes = source.getBytes();
            //执行加密
            byte[] output = messageDigest.digest(bytes);
            //创建BigInteger对象
            int signum = 1;
            BigInteger bigInteger = new BigInteger(1, output);
            //按照16进制将bigeInteger的值转换为字符串
            int radix = 16;
            String encoded  = bigInteger.toString(radix).toUpperCase();
            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
